package com.dr.web.controllers;

import com.dr.common.pojo.RepMess;
import com.dr.common.ution.StringUtil;
import com.dr.common.ution.StringUtils;
import com.dr.common.ution.UploadImages;
import com.dr.exception.ServiceExcep;
import com.dr.pojo.*;
import com.dr.service.*;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by tugou on 2017/4/23.
 * 后台用户控制器
 */
@Controller
@RequestMapping("sys")
public class SysUserController {
    @Autowired
    SysLoginService sysLoginService;
    @Autowired
    StudentInfoService studentInfoService;
    @Autowired
    LocationService locationService;
    @Autowired
    SysConfigService sysConfigService;

    private static Integer pageSize = 5;


    @Autowired
    WeChatUserInfoService weChatUserInfoService;

    /**
     * 获取学员微信详细信息
     *
     * @param model
     * @param session
     * @return
     */
    @RequestMapping(value = "index/{pageNum}", method = RequestMethod.GET)
    public String getWeChatUserInfo(Model model, HttpSession session, @PathVariable Integer pageNum) {
        if (pageNum == null) {
            pageNum = 1;
        }
        PageInfo<WeChatUserInfo> pageInfo = weChatUserInfoService.getWeChatUserInfoList(null, pageNum, pageSize);
        SysUser sysuser = (SysUser) session.getAttribute("sysuser");
        model.addAttribute("sysuser", sysuser);
        model.addAttribute("weChatUser", pageInfo.getList());
        model.addAttribute("total", pageInfo.getTotal());
        model.addAttribute("pageNum", pageNum);
        model.addAttribute("pageSize", pageInfo.getPages());
        return "background/index";
    }

    @RequestMapping(value = "userList", method = RequestMethod.GET)
    public String userList(Model model, HttpSession session) {
        List<SysUser> list = sysLoginService.getUserList();
        SysUser sysuser = (SysUser) session.getAttribute("sysuser");
        model.addAttribute("sysuser", sysuser);
        model.addAttribute("userList", list);
        return "background/userList";
    }

    @RequestMapping(value = "addUser", method = RequestMethod.GET)
    public String addUserPage(Model model, HttpSession session) {
        SysUser sysuser = (SysUser) session.getAttribute("sysuser");
        model.addAttribute("sysuser", sysuser);
        return "background/userAdd";
    }

    @RequestMapping(value = "addUser", method = RequestMethod.POST)
    public String addUser(Model model, HttpSession session, SysUser user) {
        RepMess msg = new RepMess();
        SysUser sysuser = (SysUser) session.getAttribute("sysuser");
        model.addAttribute("sysuser", sysuser);
        try {
            sysLoginService.saveSysUser(user);
            msg.setErrmsg("添加成功");
            List<SysUser> list = sysLoginService.getUserList();
            model.addAttribute("userList", list);
            model.addAttribute("msg", msg);
            return "background/userList";
        } catch (ServiceExcep excep) {
            msg.setErrmsg(excep.getMsg());
            model.addAttribute("user", user);
            model.addAttribute("msg", msg);
            return "background/userAdd";
        }
    }


    @RequestMapping("saveSysUser")
    public String saveSysUser(SysUser sysUser, Model model, HttpSession session) {
        SysUser user = (SysUser) session.getAttribute("sysuser");
        return null;
    }

    @RequestMapping(value = "getStudentList", produces = "text/html;charset=UTF-8")
    public String getStudentList(Student student, Model model, HttpSession session, HttpServletResponse response) {
        List<Student> list = studentInfoService.getStudentList(student);
        List<Location> list2 = locationService.getAllLocation(null);
        SysUser sysuser = (SysUser) session.getAttribute("sysuser");
        model.addAttribute("sysuser", sysuser);
        model.addAttribute("studentList", list);
        model.addAttribute("locationList", list2);
        model.addAttribute("student", student);
        return "background/studentList";
    }

    @RequestMapping(value = "download/{id}")
    public ResponseEntity<byte[]> download(@PathVariable String id) throws ServiceExcep {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", "学员信息.zip");
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        try {
            byte[] zip = studentInfoService.getStudentInfoFile(id);
            return new ResponseEntity<byte[]>(zip, headers, HttpStatus.CREATED);
        } catch (ServiceExcep e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping(value = "examsPage", produces = "text/html;charset=UTF-8", method = RequestMethod.GET)
    public String examsPage(Model model, HttpSession session) {
        List<Location> list = locationService.getAllLocation(null);
        SysUser sysuser = (SysUser) session.getAttribute("sysuser");
        model.addAttribute("sysuser", sysuser);
        model.addAttribute("locationList", list);
        return "background/exams";
    }

    @RequestMapping(value = "addExamsPage", produces = "text/html;charset=UTF-8", method = RequestMethod.GET)
    public String addExamsPage(Model model, String id) {
        if (StringUtil.isNotEmpty(id)) {
            Location loc = locationService.getLocationById(id);
            model.addAttribute("loc", loc);
        }
        return "background/examsAdd";
    }

    @RequestMapping(value = "commitExams", method = RequestMethod.POST)
    public String commitExams(Location location, @RequestParam("file") MultipartFile file, HttpServletRequest request) {
        try {
            if (location.getId() != null) {
                location.setBgPicture(locationService.getLocationById(location.getId().toString()).getBgPicture());
            }
            if (file != null && file.getSize() != 0) {
                String filePath = UploadImages.saveFile(file, request, location.getBgPicture());
                location.setBgPicture(filePath);
            }
            locationService.commitLocation(location);
        } catch (ServiceExcep excep) {
            excep.printStackTrace();
        }
        return "redirect:/sys/examsPage";
    }

    @RequestMapping(value = "deleteExams", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> deleteExams(Model model, String id) {
        Map<String, String> result = new HashMap<>();
        try {
            locationService.deleteLocation(id);
            result.put("code", "00000");
            result.put("msg", "OK");
            return result;
        } catch (ServiceExcep excep) {
            result.put("code", "100001");
            result.put("msg", excep.getMessage());
            return result;
        }
    }

    @RequestMapping(value = "settingPage", method = RequestMethod.GET)
    public String settingPage(Model model, HttpSession session) {
        List<SysConfig> list = sysConfigService.getConfigList();
        SysUser sysuser = (SysUser) session.getAttribute("sysuser");
        model.addAttribute("sysuser", sysuser);
        model.addAttribute("SysConfig", list);
        return "background/configSetting";
    }

    @RequestMapping(value = "addSetting", method = RequestMethod.GET)
    public String addSetting(Model model, HttpSession session, Long id) {
        if (id != null) {
            SysConfig config = new SysConfig();
            config.setId(id);
            List<SysConfig> list = sysConfigService.getSysConfig(config);
            if (list != null && list.size() > 0) {
                model.addAttribute("sysConfig", list.get(0));
            }
        }
        SysUser sysuser = (SysUser) session.getAttribute("sysuser");
        model.addAttribute("sysuser", sysuser);
        return "background/configSettingAdd";
    }

    @RequestMapping(value = "addSetting", method = RequestMethod.POST)
    public String addSettingCommit(Model model, HttpSession session, SysConfig config) {
        try {
            sysConfigService.commitConfig(config);
        } catch (ServiceExcep excep) {
            excep.printStackTrace();
        }
        SysUser sysuser = (SysUser) session.getAttribute("sysuser");
        model.addAttribute("sysuser", sysuser);
        return "redirect:/sys/settingPage";
    }

    @RequestMapping(value = "changePaw", method = RequestMethod.GET)
    public String changePassword(Model model, HttpSession session) {
        SysUser sysuser = (SysUser) session.getAttribute("sysuser");
        model.addAttribute("sysuser", sysuser);
        return "background/changePaw";
    }

    @RequestMapping(value = "commitChange", method = RequestMethod.POST)
    public String commitChange(Model model, SysUser sysuser, HttpSession session) {
        RepMess msg = new RepMess();
        while (true) {
            SysUser sys = (SysUser) session.getAttribute("sysuser");
            if (StringUtil.isEmpty(sysuser.getUserName())) {
                msg.setErrmsg("真实姓名不能为空");
            }
            if (StringUtils.isEmpty(sysuser.getOlderPassword())) {
                msg.setErrmsg("原密码不能为空");
                break;
            }
            if (!sys.getUserPwd().equals(sysuser.getOlderPassword())) {
                msg.setErrmsg("原密码不正确!");
                break;
            }
            if (StringUtils.isEmpty(sysuser.getUserPwd())) {
                msg.setErrmsg("确认密码不能为空!");
                break;
            }
            try {
                int resultCount = sysLoginService.updateSysUser(sysuser);
                if (resultCount == 1)
                    msg.setErrmsg("密码修改成功！");
                else
                    msg.setErrmsg("密码修改失败!");
                break;
            } catch (ServiceExcep excep) {
                excep.printStackTrace();
            }
            break;
        }
        model.addAttribute("msg", msg);
        return "background/changePaw";
    }
}
